package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if (dto.getEquipmentId() == null && (StringUtils.isBlank(dto.getPhone())&&StringUtils.isBlank(dto.getPassword()))) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询登录用户
      if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
          ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                  .eq(ApUser::getStatus, 0).eq(ApUser::getPhone, dto.getPhone()));
          if (apUser==null){
              throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号错误，请重新输入");
          }
          // 数据库密码
          String password = apUser.getPassword();
          String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
          if (!password.equals(inputPwd)){
              throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
          }
       Map<String, Object> map = new HashMap<>();
          apUser.setSalt("");
          apUser.setPassword("");
          map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
          map.put("apUser",apUser);
          return ResponseResult.okResult(map);
      }else {
          Map<String,Object> map = new HashMap<>();
          // 通过设备ID登录的 userId存0
          map.put("token",AppJwtUtil.getToken(0L));
          return ResponseResult.okResult(map);
      }
    }
}
